// function preloader(){
//     document.getElementById("loadingMain").style.display = "none";
//     document.getElementById("main").style.display = "block";
// }//preloader
// window.onload = preloader;

function carousel(){
  $('#myCarousel').carousel({
    interval: 4000
  });
  $('.thumbnail img').galleryFocus({
    'fadeTo': 0.5
  });
  // handles the carousel thumbnails
  $('[id^=carousel-selector-]').click( function(){
    var id_selector = $(this).attr("id");
    var dataId = id_selector.split('-');
    id = parseInt(dataId[2]);
    $('#myCarousel').carousel(id);
    $('[id^=carousel-selector-]').removeClass('selected');
    $(this).addClass('selected');
  });

  // when the carousel slides, auto update
  $('#myCarousel').on('slid', function (e) {
    var id = $('.item.active').data('slide-number');
    id = parseInt(id);
    $('[id^=carousel-selector-]').removeClass('selected');
    $('[id=carousel-selector-'+id+']').addClass('selected');
  });
}

function stripTrailingSlash(str) {
  if(str.substr(-1) == '/') {
    return str.substr(0, str.length - 1);
  }
  return str;
}

$(document).ready(function(){
  $('#loadingMain').fadeOut();
  
  $('html body').mousemove(function(e){
    var amountMovedX = (e.pageX * -1 / 50);
    var amountMovedY = (e.pageY * -1 / 50);
    $('#img img').css({
      'top': amountMovedX + 'px ',
      'left':  amountMovedY + 'px'
    });
  });

  $('.scrollNice').mCustomScrollbar();

  var socket = io.connect( 'http://116.118.112.25:8889' );
  var ipAddress = "";
  $.get("http://jsonip.com?callback=?", function(response) {
		ipAddress = response.ip;
		var arrIp = ipAddress.split(", ");
		if(arrIp.length == 2){
			ipAddress = arrIp[1];
		}
	}, "jsonp");
	$('#btn-input').keyup(function(e) { 
		if (e.keyCode == 13) {
			// var nameVal = $( "#nameInput" ).val();
			var msg = $(this).val();
			var maxLength = $(this).attr("maxlength");  
			var length = msg.length;
			// send 
			if (length <= maxLength + 1) {
				socket.emit( 'message', { ipaddress: ipAddress, message: msg, type:2 } );

				// Ajax call for saving datas
				$.ajax({
					url: $base_url+"home/ajax/chat",
					type: "POST",
					data: { message: msg, ipAddress: ipAddress }
				});
				$(this).val("");
			} else {
				$(this).val(msg.substring(0, maxLength));
			}

		return false;
	}
  });

  socket.on( 'message', function( data ) {
      // var actualContent = $( "#messages" ).html();
      // var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
      // var content = newMsgContent + actualContent;
	
      // $( "#messages" ).html( content );
	if(data.ipaddress == ipAddress){
		var d = new Date();

		var month = d.getMonth()+1;
		var day = d.getDate();

		var output = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;

		var time = (d.getHours() < 10 ? '0' : '') + d.getHours() + ":" + (d.getMinutes() < 10 ? '0' : '') + d.getMinutes() + ":" + d.getSeconds();
		var timeFull = output+" "+time;
		if(data.type != 1){
			var $content = '<li class="right clearfix"><span class="chat-img pull-right">';
		  $content += '<img src="'+ $base_url +'public/templates/home/images/guest.gif" alt="Guest Avatar" class="img-circle" /></span>';
		  $content += '<div class="chat-body clearfix"><div class="header"><small class=" text-muted"><span class="glyphicon glyphicon-time">';
		  $content += '</span><abbr class="timeago" title="'+timeFull+'"></abbr></small><strong class="pull-right primary-font">Guest</strong></div><p>'+data.message+'</p></div></li>';
		}else{
			var $content = '<li class="left clearfix"><span class="chat-img pull-left">';
		  $content += '<img src="'+ $base_url +'public/templates/home/images/admin.gif" alt="Admin Avatar" class="img-circle" /></span>';
		  $content += '<div class="chat-body clearfix"><div class="header"><small class=" text-muted"><span class="glyphicon glyphicon-time">';
		  $content += '</span><abbr class="timeago" title="'+timeFull+'"></abbr></small><strong class="pull-right primary-font">Admin</strong></div><p>'+data.message+'</p></div></li>';
		}
      $('.chat').append($("<p>"+ $content +"</p>"));
      //$('.chat').scrollTop = $('.chat').scrollHeight;
	  $(".panel-body").animate({ scrollTop: $('.panel-body')[0].scrollHeight}, 1000);
	  jQuery("abbr.timeago").timeago();
	}
  });

  var hiddenContent = $( "#box_chat" );
  $(".toggleup").click(function(){
    hiddenContent.slideToggle();
	$.ajax({
	  url: $base_url+"home/ajax/showChat",
	  type: "POST",
	  success: function(data) {
		data = JSON.parse(data);
		if(data.text){
		  for (var i = 0; i < data.text.length; i++) {
			var dataMessage = data.text[i];
			var arrDataMessage = dataMessage.split("|");
			var $content;
			if(arrDataMessage[0] != 1){
				var $content = '<li class="right clearfix"><span class="chat-img pull-right">';
				$content += '<img src="'+ $base_url +'public/templates/home/images/guest.gif" alt="Guest Avatar" class="img-circle" /></span>';
				$content += '<div class="chat-body clearfix"><div class="header"><small class=" text-muted"><span class="glyphicon glyphicon-time">';
				$content += '</span><abbr class="timeago" title="'+arrDataMessage[1]+'"></abbr></small><strong class="pull-right primary-font">Guest</strong></div><p>'+arrDataMessage[2]+'</p></div></li>';
			}else{
				var $content = '<li class="left clearfix"><span class="chat-img pull-left">';
				$content += '<img src="'+ $base_url +'public/templates/home/images/admin.gif" alt="Admin Avatar" class="img-circle" /></span>';
				$content += '<div class="chat-body clearfix"><div class="header"><small class=" text-muted"><span class="glyphicon glyphicon-time">';
				$content += '</span><abbr class="timeago" title="'+arrDataMessage[1]+'"></abbr></small><strong class="pull-right primary-font">Admin</strong></div><p>'+arrDataMessage[2]+'</p></div></li>';
			}
			$('.chat').append($content);
		  }             
			jQuery("abbr.timeago").timeago();
		}
		$(".panel-body").animate({ scrollTop: $('.panel-body')[0].scrollHeight}, 1000);
	  }
	});
  });

  $(".dropdown-toggle").click(function(){
    hiddenContent.slideToggle();
  });

  var url = window.location.href; 
  var activePage = stripTrailingSlash(url);
  $('.nav li a').each(function(){  
    var currentPage = stripTrailingSlash($(this).attr('href'));
    if (activePage == currentPage) {
      $(this).parent().addClass('active'); 
    }else{
      $(this).parent().removeClass('active'); 
    } 
  });

  $(".changeGallery").click(function(){
    var galleryId = $(this).attr('ids');
    $.ajax({
      type: "POST",
      url: $base_url+"home/ajax/changeGallery",
      data: 'id='+galleryId,
      success: function(data){
        data = JSON.parse(data);
        $("#carouselCustom").html(data.html);
        carousel();
      },
    });
  })

  carousel();
});